package com.hoyue.classroom.controller;

import com.hoyue.classroom.bean.Course;
import com.hoyue.classroom.service.CourseService;
import com.hoyue.classroom.service.GroupService;
import com.hoyue.classroom.service.MemberService;
import com.hoyue.common.utils.Base64Utils;
import com.hoyue.common.utils.RUtils;
import com.hoyue.system.bean.User;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;

/**
 * 成员控制器
 * @author 空白
 * @version 1.0
 * Create by 2019/08/27 21:53
 */
@Controller
@RequestMapping("/member")
public class MemberController {

    private String prefix = "member";

    @Autowired
    MemberService memberService;

    @Autowired
    CourseService courseService;

    @Autowired
    GroupService groupService;

    /**
     * 显示该课程所有学生
     * @param model
     * @param session
     * @return
     */
    @GetMapping("/list")
    public String List(Model model, HttpSession session) {
        // 从session中获取课程id
        Course course = (Course) session.getAttribute("course");
        List<User> students = memberService.ListMember(course.getId());
        model.addAttribute("students", students);
        model.addAttribute("CourseCode", Base64Utils.encode(course.getId()));
        model.addAttribute("studentSize", students.size());
        return prefix + "/member";
    }

    /**
     * 教师移除学生（教师拥有权限）
     * @param userId 待移除学生
     * @param courseId 该课程id
     * @return
     */
    @RequiresRoles("teacher")
    @RequestMapping("/remove")
    public RUtils Remove(Integer userId, Integer courseId) {
        if (courseService.outCourse(userId, courseId) > 0) {
            return RUtils.ok();
        }
        else {
            return RUtils.error(1, "移除成功");
        }
    }

    /**
     * 教师批量移除学生（教师拥有权限）
     * @param userId 待移除学生
     * @param courseId 该课程id
     * @return
     */
    @RequiresRoles("teacher")
    @RequestMapping("/removes")
    public RUtils Removes(Set<Integer> userId, Integer courseId) {
        boolean flag = true;
        for (Integer uId: userId) {
            if (courseService.outCourse(uId, courseId) <= 0) {
                flag = false;
            }
        }
        if (flag) {
            return RUtils.ok();
        }
        else {
            return RUtils.error(1, "批量移除失败");
        }
    }
}
